var http = require('http')
var fs = require('fs')
const router = require('./router')
const imgscan = require('./utils/scanImgFile')
const generateCode = require('./utils/generateCode')
const struils = require('./utils/stringUtil')

// 默认显示当天的图片
var showSetting = 'day'
var isNeedGenerate = true

function minusDays(DateA, DateB) {
  var time1 = Date.parse(DateA)
  var time2 = Date.parse(DateB)
  var nDays = Math.abs(parseInt((time2 - time1) / 1000 / 3600 / 24))
  return nDays
}

function getFileByDate(keys) {
  for (var i = 0; keys != undefined && keys != null && i < keys.length; i++) {
    var key = keys[i]
    daylist = []
    weeklist = []
    monthlist = []
    yearlist = []
    fs.stat(__dirname + '/public/' + key, (error, stats) => {
      if (stats) {
        var fileDate = new Date(stats['birthtime'])
        var currentDate = new Date()
        var days = minusDays(currentDate, fileDate)
        if (days < 1) daylist.push(days)
        else if (days < 7) weeklist.push(days)
        if (days < 30) monthlist.push(days)
        if (days < 365) yearlist.push(days)
      }
    })
  }
  if (showSetting == 'day') return daylist
  if (showSetting == 'week') return weeklist
  if (showSetting == 'month') return monthlist
  return yearlist
}

function start() {
  const server = http.createServer(function (req, res) {
    var url = ''
    if (struils.trim(req.url) == '/') url = ''
    else url = struils.trim(req.url.substring(1))
    var links = url.split('?')
    if (links.length != 1) {
      showSetting = links[1].split('=')[1]
    }

    // 显示内容
    router.processRoute(req, res)

    // 扫描文件
    var keys = imgscan.scan(req, res)
    // 根据文件日期丢弃部分数据
    keys = getFileByDate(keys)
    if (keys.length != 0 && isNeedGenerate) {
      console.log(123)
      generateCode.process(keys)
      isNeedGenerate = false
    }
  })

  server.listen(3001, 'localhost', () => {
    console.log(`Server running at http://localhost:3001/`)
  })
}

exports.start = start
